package org.erp.spu.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.handler.inter.IExcelExportServer;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.erp.common.domain.Result;
import org.erp.spu.entity.SpuReleaseInfo;
import org.erp.spu.entity.vo.*;
import org.erp.spu.service.ExcelImportExportService;
import org.springframework.web.bind.annotation.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static cn.hutool.poi.excel.ExcelUtil.XLSX_CONTENT_TYPE;

/**
 * 文件导出
 */
@RestController
@RequestMapping("/excel/export")
@Log4j2
public class ExcelImportExportController {


    @Resource
    private ExcelImportExportService excelImportExportService;

  
    /**
     * 全量属性值大数据导出（按分类ID）
     * pageSize最大5000
     */
    @GetMapping("/allAttr")
    public void allAttrBig(@NotNull(message = "分类ID不能为空") Long categoryId,
                           Integer pageSize,
                           HttpServletResponse response) throws IOException {
        int size = normalizePageSize(pageSize);

        ExportParams params = exportParams("全量参数", "属性明细");

        IExcelExportServer server = new IExcelExportServer() {
            @Override
            public List<Object> selectListForExcelExport(Object queryParams, int page) {
                List<SpuAttrExcelVo> pageList =
                        excelImportExportService.getSpuAllExportListByCategoryIdByPage(categoryId, page, size);
                return pageList == null ? null : new java.util.ArrayList<Object>(pageList);
            }
        };

        Workbook wb = ExcelExportUtil.exportBigExcel(params, SpuAttrExcelVo.class, server, null);
        String fileName = buildFileName("全量参数");
        writeWorkbookToResponse(response, wb, fileName);
      
    }

    /**
     * 全量发布项值导出
     */
    @GetMapping("/allRelease")
    public void allRelease(@NotNull(message = "分类ID不能为空") Long categoryId,
                           HttpServletResponse response) throws IOException {
        List<SpuAllReleaseExcelVo> allReleaseExportList = excelImportExportService.getSpuAllReleaseExportListByCategoryId(categoryId);
        
        ExportParams params = exportParams("全量发布项", "发布项明细");
        // EasyPOI 在导出过程中会对传入的集合执行 remove 操作，
        // 若传入的是不可变集合（例如 List.of/Collections.unmodifiableList），将抛出 UnsupportedOperationException。
        // 因此这里确保传入的是一个可变的 ArrayList。
        List<SpuAllReleaseExcelVo> exportList =
                (allReleaseExportList == null) ? new java.util.ArrayList<>() : new java.util.ArrayList<>(allReleaseExportList);
        Workbook wb = ExcelExportUtil.exportExcel(params, SpuAllReleaseExcelVo.class, exportList);
        String fileName = buildFileName("全量发布项");
        writeWorkbookToResponse(response, wb, fileName);
    }

    /**
     * 发布组发布项导出
     */
     @GetMapping("/releaseGroup")
      public void releaseGroupRelease(@NotNull(message = "分类ID不能为空") Long categoryId,
                           HttpServletResponse response) throws IOException {
         List<SpuReleaseInfo> releaseList = excelImportExportService.getSpuReleaseListByCategoryId(categoryId);
         ExportParams params = exportParams("发布组发布项", "发布项明细");

         List<SpuReleaseInfo> exportList =
                 (releaseList == null) ? new java.util.ArrayList<>() : new java.util.ArrayList<>(releaseList);
                 Workbook wb = ExcelExportUtil.exportExcel(params, SpuReleaseInfo.class, exportList);
                 String fileName = buildFileName("发布组发布项");
                 writeWorkbookToResponse(response, wb, fileName);
    }


    /**
     * 机型模版大数据导出（按分类ID）
     * pageSize最大5000
     */
    @GetMapping("/model/template")
    public void modelTemplateBig(@NotNull(message = "分类ID不能为空") Long categoryId,
                           Integer pageSize,
                           HttpServletResponse response) throws IOException {
        int size = normalizePageSize(pageSize);

        ExportParams params = exportParams("机型发布模版", "机型发布模版");

        IExcelExportServer server = new IExcelExportServer() {
            @Override
            public List<Object> selectListForExcelExport(Object queryParams, int page) {
                List<SpuModelTemplateExcelVo> pageList =
                        excelImportExportService.getModelTemplateExportByCategoryId(categoryId, page, size);
                return pageList == null ? null : new java.util.ArrayList<Object>(pageList);
            }
        };
        Workbook wb = ExcelExportUtil.exportBigExcel(params, SpuModelTemplateExcelVo.class, server, null);
        String fileName = buildFileName("机型发布模版");
        writeWorkbookToResponse(response, wb, fileName);

    }

    /**
     * 模版对应版本号导出
     */
    @GetMapping("/templateInfo")
    public void templateInfoList(@NotNull(message = "分类ID不能为空") Long categoryId,HttpServletResponse  response) throws  IOException{
        List<SpuTemplateInfoVo> templateInfoList = excelImportExportService.getTemplateInfoList(categoryId);
        ExportParams params = exportParams("模版对应版本号", "模版对应版本号");
        List<SpuTemplateInfoVo> exportList =
                (templateInfoList == null) ? new java.util.ArrayList<>() : new java.util.ArrayList<>(templateInfoList);
        Workbook wb = ExcelExportUtil.exportExcel(params, SpuTemplateInfoVo.class, exportList);
        String fileName = buildFileName("模版对应版本号");
        writeWorkbookToResponse(response, wb, fileName);
    }

    /**
     * 模版发布项导出
     */
    @GetMapping("/templateReleaseList")
    public void templateReleaseList(@NotNull(message = "模版ID不能为空") Long templateId,HttpServletResponse  response) throws  IOException{
        List<SpuTemplateReleaseExcelVo> templateReleaseList = excelImportExportService.getReleaseListByTemplateId(templateId);
        ExportParams params = exportParams("发布模版", "发布模版");
        List<SpuTemplateReleaseExcelVo> exportList =
                (templateReleaseList == null) ? new java.util.ArrayList<>() : new java.util.ArrayList<>(templateReleaseList);
        Workbook wb = ExcelExportUtil.exportExcel(params, SpuTemplateReleaseExcelVo.class, exportList);
        String fileName = buildFileName("发布模版");
        writeWorkbookToResponse(response, wb, fileName);

    }


    /**
     * 上传全量参数Excel并导入数据
     */
    @PostMapping("/importAttrExcel")
    public Result<String> importAttrExcel(@RequestParam("file") MultipartFile file) {
        String summary = excelImportExportService.importAttrExcel(file);
        return Result.success(summary);
    }

    /**
     * 上传发布项Excel并导入数据
     */
    @PostMapping("importReleaseExcel")
    public Result<String> importReleaseExcel(@RequestParam("file") MultipartFile file) {
        String summary = excelImportExportService.importReleaseExcel(file);
        return Result.success(summary);
    }

    /**
     * 上传发布项Excel并导入数据（按模版）
     */
    @PostMapping("/importReleaseExcelByTemplate")
    public Result<String> importReleaseExcelByTemplate(@RequestParam("file") MultipartFile file) {
        String summary = excelImportExportService.importReleaseExcelByTemplate(file);
        return Result.success(summary);
    }
    /**
     * 上传机型模版Excel并导入数据
     */
    @PostMapping("/importModelTemplate")
    public Result<String> importModelTemplate(@RequestParam("file") MultipartFile file) {
        String summary = excelImportExportService.importModelTemplate(file);
        return Result.success(summary);
    }

    private ExportParams exportParams(String title, String sheetName) {
        return new ExportParams(title, sheetName);
    }

    private String buildFileName(String baseName) {
        return baseName + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";
    }
    
    private int normalizePageSize(Integer pageSize) {
        int size = (pageSize == null) ? 5000 : pageSize;
        if (size <= 0) size = 5000;
        if (size > 5000) size = 5000; // 上限保护
        return size;
    }

    private void writeWorkbookToResponse(HttpServletResponse response, Workbook wb, String fileName) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(XLSX_CONTENT_TYPE);
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        try {
            wb.write(response.getOutputStream());
            response.flushBuffer();
            log.info("Excel 导出完成: {}", fileName);
        } finally {
            try {
                wb.close();
            } catch (IOException ignore) {
            }
        }
    }







}
